package com.cristina.attention.handler.chat.simple;

import com.cristina.attention.annotation.SyncChat;
import com.cristina.attention.codec.Invocation;
import com.cristina.attention.dispatcher.MessageHandler;
import com.cristina.attention.message.chat.ChatSendResponse;
import com.cristina.attention.manager.NettyChannelManager;
import com.cristina.attention.message.chat.ChatRedirect;
import com.cristina.attention.message.chat.simple.SendSimpleChat;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 服务端处理客户端的私聊请求
 * 一对一
 *
 * @Author superman
 * @Date 2021/9/19 20:57
 **/
@Component
public class SendSimpleChatHandler implements MessageHandler<SendSimpleChat> {

    @Resource
    private NettyChannelManager nettyChannelManager;

    @Override
    @SyncChat
    public void execute(Channel channel, SendSimpleChat message) {
        // 客户端发送消息到服务端, 并响应
        ChatSendResponse response = new ChatSendResponse().setMessageId(message.getMessageId()).setCode(200);
        channel.writeAndFlush(new Invocation(ChatSendResponse.TYPE, response));

        // 转发给指定用户
        ChatRedirect sendToUserRequest = ChatRedirect.builder()
                .messageId(message.getMessageId())
                .content(message.getContent())
                .sendId(String.valueOf(message.getSendId()))
                .receiveId(String.valueOf(message.getReceiveId())).build();
        nettyChannelManager.send(message.getReceiveId(), new Invocation(ChatRedirect.TYPE, sendToUserRequest));
    }

    @Override
    public String getType() {
        return SendSimpleChat.TYPE;
    }
}
